using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using ComponentSystem;
using Cysharp.Threading.Tasks;
using UnityEngine;

namespace UnityActionSystem
{
    /// <summary>
    /// 事件总线 - 高性能事件系统核心管理器
    /// </summary>
    public class EventBusEntity : EntityCSharp
    {
        private static EventBusEntity _instance;

        /// <summary>
        /// 事件监听器委托
        /// </summary>
        /// <typeparam name="T">事件数据类型</typeparam>
        /// <param name="eventData">事件数据</param>
        public delegate void EventHandler<T>(T eventData) where T : EventDataBase;

        /// <summary>
        /// 事件队列项
        /// </summary>
        private struct EventQueueItem
        {
            public string EventId;
            public EventDataBase EventData;
            public EventPriority Priority;
            public float QueueTime;
        }

        // 事件监听器存储
        private readonly Dictionary<string, List<Delegate>> _eventHandlers = new Dictionary<string, List<Delegate>>();

        // 三个独立的优先级队列
        private readonly Queue<EventQueueItem> _highPriorityQueue = new Queue<EventQueueItem>();
        private readonly Queue<EventQueueItem> _normalPriorityQueue = new Queue<EventQueueItem>();
        private readonly Queue<EventQueueItem> _lowPriorityQueue = new Queue<EventQueueItem>();

        // 每帧处理的事件数量限制
        private const int MaxEventsPerFrame = 10;

        // 取消令牌
        private CancellationTokenSource _cancellationTokenSource;

        // 是否正在处理事件
        private bool _isProcessingEvents = false;

        public override void Initialization()
        {
            base.Initialization();

            if (_instance != null)
                return;

            _instance = this;
            InitializeEventBus();

        }

        private void Clear()
        {
            // 先取消令牌，停止异步任务
            _cancellationTokenSource?.Cancel();

            // 等待一小段时间确保异步任务完成
            if (_cancellationTokenSource != null)
            {
                try
                {
                    // 给异步任务一点时间完成清理
                    System.Threading.Thread.Sleep(10);
                }
                catch
                {
                    // 忽略线程睡眠异常
                }
            }

            // 清理资源
            _cancellationTokenSource?.Dispose();
            _eventHandlers.Clear();
            _highPriorityQueue.Clear();
            _normalPriorityQueue.Clear();
            _lowPriorityQueue.Clear();

            // 重置单例实例
            if (_instance == this)
            {
                _instance = null;
            }
        }

        /// <summary>
        /// 初始化事件总线
        /// </summary>
        private void InitializeEventBus()
        {
            _cancellationTokenSource = new CancellationTokenSource();
            StartEventProcessingLoop().Forget();
        }

        /// <summary>
        /// 订阅事件
        /// </summary>
        /// <typeparam name="T">事件数据类型</typeparam>
        /// <param name="eventId">事件ID</param>
        /// <param name="handler">事件处理器</param>
        public void Subscribe<T>(string eventId, EventHandler<T> handler) where T : EventDataBase
        {
            // 防御性检查：防止销毁后调用
            if (_cancellationTokenSource?.IsCancellationRequested == true)
            {
                Debug.LogWarning("EventBus已销毁，无法订阅事件");
                return;
            }

            if (string.IsNullOrEmpty(eventId))
            {
                Debug.LogError("EventBus.Subscribe: eventId不能为空");
                return;
            }

            if (handler == null)
            {
                Debug.LogError("EventBus.Subscribe: handler不能为空");
                return;
            }

            if (!_eventHandlers.ContainsKey(eventId))
            {
                _eventHandlers[eventId] = new List<Delegate>();
            }

            _eventHandlers[eventId].Add(handler);
        }

        /// <summary>
        /// 取消订阅事件
        /// </summary>
        /// <typeparam name="T">事件数据类型</typeparam>
        /// <param name="eventId">事件ID</param>
        /// <param name="handler">事件处理器</param>
        public void Unsubscribe<T>(string eventId, EventHandler<T> handler) where T : EventDataBase
        {
            // 防御性检查：防止销毁后调用
            if (_cancellationTokenSource?.IsCancellationRequested == true)
            {
                return; // 销毁后静默返回
            }

            if (string.IsNullOrEmpty(eventId) || handler == null)
                return;

            if (_eventHandlers.ContainsKey(eventId))
            {
                _eventHandlers[eventId].Remove(handler);

                // 如果没有监听器了，移除整个事件
                if (_eventHandlers[eventId].Count == 0)
                {
                    _eventHandlers.Remove(eventId);
                }
            }
        }

        /// <summary>
        /// 发布事件
        /// </summary>
        /// <typeparam name="T">事件数据类型</typeparam>
        /// <param name="eventId">事件ID</param>
        /// <param name="eventData">事件数据</param>
        /// <param name="priority">事件优先级</param>
        public void Publish<T>(string eventId, T eventData, EventPriority priority = EventPriority.Normal) where T : EventDataBase
        {
            // 防御性检查：防止销毁后调用
            if (_cancellationTokenSource?.IsCancellationRequested == true)
            {
                Debug.LogWarning("EventBus已销毁，无法发布事件");
                return;
            }

            if (string.IsNullOrEmpty(eventId))
            {
                Debug.LogError("EventBus.Publish: eventId不能为空");
                return;
            }

            if (eventData == null)
            {
                Debug.LogError("EventBus.Publish: eventData不能为空");
                return;
            }

            // 根据优先级选择处理方式
            switch (priority)
            {
                case EventPriority.Immediate:
                    ProcessEventImmediately(eventId, eventData);
                    break;

                case EventPriority.High:
                case EventPriority.Normal:
                case EventPriority.Low:
                    EnqueueEvent(eventId, eventData, priority);
                    break;
            }
        }

        /// <summary>
        /// 立即处理事件
        /// </summary>
        private void ProcessEventImmediately(string eventId, EventDataBase eventData)
        {
            if (!_eventHandlers.ContainsKey(eventId))
                return;

            var handlers = _eventHandlers[eventId];
            // 创建副本避免迭代时被修改
            var handlersCopy = new Delegate[handlers.Count];
            handlers.CopyTo(handlersCopy);

            for (int i = 0; i < handlersCopy.Length; i++)
            {
                try
                {
                    handlersCopy[i].DynamicInvoke(eventData);
                }
                catch (Exception e)
                {
                    Debug.LogError($"EventBus处理事件{eventId}时发生错误: {e}");
                }
            }
        }

        /// <summary>
        /// 将事件加入队列
        /// </summary>
        private void EnqueueEvent(string eventId, EventDataBase eventData, EventPriority priority)
        {
            var queueItem = new EventQueueItem
            {
                EventId = eventId,
                EventData = eventData,
                Priority = priority,
                QueueTime = Time.time
            };

            switch (priority)
            {
                case EventPriority.High:
                    _highPriorityQueue.Enqueue(queueItem);
                    break;
                case EventPriority.Normal:
                    _normalPriorityQueue.Enqueue(queueItem);
                    break;
                case EventPriority.Low:
                    _lowPriorityQueue.Enqueue(queueItem);
                    break;
            }
        }

        /// <summary>
        /// 启动事件处理循环
        /// </summary>
        private async UniTask StartEventProcessingLoop()
        {
            while (!_cancellationTokenSource.Token.IsCancellationRequested)
            {
                try
                {
                    await ProcessEventQueue();
                    await UniTask.Yield(PlayerLoopTiming.Update, _cancellationTokenSource.Token);
                }
                catch (OperationCanceledException)
                {
                    // 正常取消，退出循环
                    break;
                }
                catch (Exception e)
                {
                    Debug.LogError($"EventBus处理循环发生错误: {e}");
                    await UniTask.Delay(100, cancellationToken: _cancellationTokenSource.Token);
                }
            }
        }

        /// <summary>
        /// 处理事件队列
        /// </summary>
        private UniTask ProcessEventQueue()
        {
            if (_isProcessingEvents)
                return UniTask.CompletedTask;

            int totalCount = _highPriorityQueue.Count + _normalPriorityQueue.Count + _lowPriorityQueue.Count;
            if (totalCount == 0)
                return UniTask.CompletedTask;

            _isProcessingEvents = true;

            try
            {
                int processedCount = 0;

                // 先处理 High 优先级
                while (_highPriorityQueue.Count > 0 && processedCount < MaxEventsPerFrame)
                {
                    var item = _highPriorityQueue.Dequeue();
                    ProcessEventImmediately(item.EventId, item.EventData);
                    processedCount++;
                }

                // 再处理 Normal 优先级
                while (_normalPriorityQueue.Count > 0 && processedCount < MaxEventsPerFrame)
                {
                    var item = _normalPriorityQueue.Dequeue();
                    ProcessEventImmediately(item.EventId, item.EventData);
                    processedCount++;
                }

                // 最后处理 Low 优先级
                while (_lowPriorityQueue.Count > 0 && processedCount < MaxEventsPerFrame)
                {
                    var item = _lowPriorityQueue.Dequeue();
                    ProcessEventImmediately(item.EventId, item.EventData);
                    processedCount++;
                }
            }
            finally
            {
                _isProcessingEvents = false;
            }

            return UniTask.CompletedTask;
        }

        /// <summary>
        /// 获取事件监听器数量
        /// </summary>
        /// <param name="eventId">事件ID</param>
        /// <returns>监听器数量</returns>
        public int GetListenerCount(string eventId)
        {
            // 防御性检查：防止销毁后调用
            if (_cancellationTokenSource?.IsCancellationRequested == true)
            {
                return 0;
            }

            return _eventHandlers.ContainsKey(eventId) ? _eventHandlers[eventId].Count : 0;
        }

        /// <summary>
        /// 获取队列中待处理的事件数量
        /// </summary>
        /// <returns>队列长度</returns>
        public int GetQueueCount()
        {
            // 防御性检查：防止销毁后调用
            if (_cancellationTokenSource?.IsCancellationRequested == true)
            {
                return 0;
            }

            return _highPriorityQueue.Count + _normalPriorityQueue.Count + _lowPriorityQueue.Count;
        }

        /// <summary>
        /// 清空事件队列
        /// </summary>
        public void ClearEventQueue()
        {
            // 防御性检查：防止销毁后调用
            if (_cancellationTokenSource?.IsCancellationRequested == true)
            {
                return;
            }

            _highPriorityQueue.Clear();
            _normalPriorityQueue.Clear();
            _lowPriorityQueue.Clear();
        }

        /// <summary>
        /// 清空所有事件监听器
        /// </summary>
        public void ClearAllListeners()
        {
            // 防御性检查：防止销毁后调用
            if (_cancellationTokenSource?.IsCancellationRequested == true)
            {
                return;
            }

            _eventHandlers.Clear();
        }
    }
}
